package com.xjy.headfirst.迭代器.复杂迭代器;


import java.util.Iterator;
import java.util.Stack;

/**
 * decription:
 *
 * @author 辛纪元
 * @since 2022-07-18
 */

public class CompositeIterator implements Iterator<MenuComponent> {

    Stack<Iterator<MenuComponent>> stack = new Stack<>();

    public CompositeIterator(Iterator<MenuComponent> iterator) {
        stack.push(iterator);
    }

    @Override
    public boolean hasNext() {
        if (stack.empty()) {
            return false;
        }
        Iterator<MenuComponent> peek = stack.peek();
        if (!peek.hasNext()) {
            stack.pop();
            return hasNext();
        }
        return true;
    }

    @Override
    public MenuComponent next() {
        if (hasNext()) {
            Iterator<MenuComponent> peek = stack.peek();
            MenuComponent next = peek.next();
            if (next instanceof Menu) {
                stack.push(next.createIterator());
            }
            return next;
        }
        return null;
    }
}
